<?php

namespace App\CustHub\Service;

use App\CustHub\Mapper\ActiveAddFriendRoomMapper;
use App\CustHub\Mapper\ChRoomMapper;
use App\CustHub\Model\ChAddFriendRoom;
use App\CustHub\Model\ChRobot;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractService;
use Mine\Annotation\Transaction;
use Mine\Exception\NormalStatusException;
use Mine\MineModel;
use function Hyperf\Collection\data_get;

class ActiveAddFriendRoomService extends AbstractService
{

    #[Inject]
    protected ActiveAddFriendConfigService $configService;

    #[Inject]
    protected ChRoomMapper $roomMapper;

    public $mapper;

    public function __construct(ActiveAddFriendRoomMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    /**
     * 设置群配置
     * @param array $params
     * @return void
     * @throws \Exception
     */
    public function upCustomRoom(array $params)
    {
        $operate_cfg = data_get($params, 'operate_cfg', 0);
        $operate_cfg=is_string($operate_cfg)?json_decode($operate_cfg,true):$operate_cfg;
        $config=$operate_cfg['draw_group_cfg'];
        $roomList = $config['rooms'];
        $max_number = data_get($config, 'max_number', 0);
        $oldRoomIds = ChAddFriendRoom::query()->where('main_uid', $params['main_uid'])
            ->where('uid', $params['uid'])
            ->where('is_new', 0)
            ->pluck('room_wxid');

        $newRoomIds = array_column($roomList, 'room_wxid');
        $newRoomIds = call_user_func_array('array_merge', array_map('array_merge', $newRoomIds));
        $robotIds = array_column($roomList, 'robot_id');
        if ($oldRoomIds->isNotEmpty()) {
            var_dump($roomList);
            $removedRoomIds = array_diff($oldRoomIds->toArray(), $newRoomIds);
            if (!empty($removedRoomIds)) {
                ChAddFriendRoom::query()->whereIn('room_wxid', $removedRoomIds)->delete();
            }
        }
        $robotWithUserIds = ChRobot::query()->whereIn('id', $robotIds)->pluck('user_id', 'id');
        //是否有拉群中的群，如果有了就全部替补
        $pushEnd = false;
        foreach ($roomList as $rooms) {
            foreach ($rooms['room_wxid'] as $room_wxid){
                $status = 2;
                $roomInfo = $this->roomMapper->findByRoomWxid($room_wxid, $params['main_uid']);
                if (!$pushEnd) {
                    //拉群中
                    if ($max_number > $roomInfo->room_member_count) {
                        $status = 1;
                        $pushEnd = true;
                    }
                }
                //群已满
                if ($max_number <= $roomInfo->room_member_count) {
                    $status = 3;
                }
                $this->mapper->model::query()->updateOrCreate([
                    'main_uid' => $params['main_uid'],
                    'uid' => $params['uid'],
                    'robot_id' => $rooms['robot_id'],
                    'room_wxid' => $room_wxid,
                ], [
                    'create_user_id' => $robotWithUserIds[$rooms['robot_id']],
                    'status' => $status,
                    'human_ceiling' => 1,
                    'is_new' => 0,
                ]);
            }
        }

    }

    public function getRoomWxIdsAndMaxNumber($uid)
    {
        $config = $this->configService->getOperateConfig(['uid' => $uid]);
        $data = $config['operate_cfg'];

        // 检查 draw_group_cfg 数组是否存在
        if (isset($data['draw_group_cfg']) && is_array($data['draw_group_cfg'])) {
            // 假设 draw_group_cfg 数组的第一个元素就是我们要找的配置（根据实际情况调整）
            $drawGroupCfg = $data['draw_group_cfg'][0];
            if (!empty($drawGroupCfg['max_number'])) {
                $maxNumber = $drawGroupCfg['max_number'];
            }
        }

        if (!$data) {
            return [];
        }
        $drawGroupCfg = data_get($data, 'draw_group_cfg', []);
        $rooms = $drawGroupCfg[0]['rooms'];

        $result = ['max_number' => $maxNumber ?? 20];
        // 遍历 "rooms" 数组
        if (isset($rooms)) {
            // 遍历 rooms 数组
            foreach ($rooms as $room) {
                $robot_id = $room['robot_id'];
                $room_wxids = $room['room_wxid'];
                // 将 room_wxids 数组添加到以 create_user_id 为键的结果数组中
                $result[$robot_id] = $room_wxids;
            }
        }

        return $result;
    }

    public function deleteRoom($params)
    {
        $ids = (array)data_get($params, 'ids', []);
        $this->mapper->realDelete($ids);
        $this->updateRoomSort($params['uid']);
        return true;
    }

    public function roomList($params)
    {
        $list = Db::table('ch_add_friend_room as a')
            ->selectRaw('a.*,c.id as robot_id,c.nickname as robot_name,c.corp_name')
            ->Leftjoin('ch_robot as c', 'c.id', '=', 'a.robot_id')
            ->where([
                ['a.is_new', '=', 0],
                ['a.uid', '=', $params['uid']],
                //['b.uid', '=', $params['uid']],
                //['c.uid', '=', $params['uid']],
            ])
            ->when(!empty($params['status']), function ($query) use ($params) {
                $query->where('a.status', $params['status']);
            })
            ->when(!empty($params['robot_id']), function ($query) use ($params) {
                $query->where('c.id', '=', $params['robot_id']);
            })
            ->orderBy('sort')
            ->paginate((int)$params['page_size'] ?? MineModel::PAGE_SIZE);
        $list->getCollection()->transform(function ($item)use($params) {
            $roomInfo=$this->roomMapper->findByRoomWxid($item->room_wxid,$params['main_uid']);
            $item->room_name=$roomInfo->room_name;
            $item->room_member_count=$roomInfo->room_member_count;
            $item->room_id=$roomInfo->id;
            return $item;
        });

        return $this->mapper->setPaginate($list);
    }

    public function updateRoomSort($uid)
    {
        // 一次性取出所有房间 id、status、sort
        $rooms = Db::table('ch_add_friend_room')
            ->where('uid', $uid)
            ->select('id', 'status', 'sort')
            ->get();

        // 检查是否存在 sort = 1
        $hasSortOne = $rooms->contains(function ($room) {
            return $room->sort == 1;
        });

        $sort = $hasSortOne ? 2 : 1;

        // 筛选出需要更新的房间
        $roomsToUpdate = $rooms->filter(function ($room) use ($hasSortOne) {
            if ($hasSortOne) {
                // 已存在 sort = 1，跳过
                return false;
            }
            // status = 3 跳过
            return $room->status !== 3;
        });

        foreach ($roomsToUpdate as $room) {
            Db::table('ch_add_friend_room')
                ->where('id', $room->id)
                ->update([
                    'sort' => $sort,
                    'status' => ($sort === 1) ? 1 : 2,
                ]);
            $sort++;
        }
    }

    #[Transaction]
    public function updateRoom(array $params)
    {
        $operate_cfg=!empty($params['operate_cfg'])?json_decode($params['operate_cfg'],true):null;
        $node_content=!empty($params['node_content'])?json_decode($params['node_content'],true):null;
        $this->configService->mapper->model::query()->updateOrCreate([
            'main_uid' => $params['main_uid'],
            'uid' => $params['uid'],
            //'corp_id' => $params['corp_id'],
        ], [
            'is_auto_node' => $params['is_auto_node'],
            'is_update_node' => $params['is_update_node'],
            'node_content' => $node_content,
            'is_auto_operate' => $params['is_auto_operate'],
            'operate_cfg' => $operate_cfg
        ]);
        $this->upCustomRoom($params);
        return true;
    }

    public function updateAddNumber($room, $contact)
    {
        DB::transaction(function () use ($room, $contact) {
            $newAddNumber = $room->add_number + 1;

            // 更新当前 room
            $updateData = ['add_number' => $newAddNumber];
            if ($newAddNumber >= $room->human_ceiling) {
                $updateData['status'] = 3;
                $updateData['sort'] = 0;
            }
            $this->mapper->model->where('id', $room->id)->update($updateData);

            // 达到上限，批量处理
            if (isset($updateData['status']) && $updateData['status'] === 3) {
                // 减 sort
                $this->mapper->model
                    ->where('uid', $contact->uid)
                    ->where('status', 2)
                    ->decrement('sort', 1);

                // sort = 1 的，状态改为 1
                $this->mapper->model
                    ->where('uid', $contact->uid)
                    ->where('status', 2)
                    ->where('sort', 1)
                    ->update(['status' => 1]);
            }
        });
    }

    public function changeRoomSort($params)
    {
        $type = data_get($params, 'direction', 'up');
        // 获取当前标签
        $currentRoom = $this->mapper->model::find($params['id'], ['id', 'uid', 'create_user_id', 'sort']);

        if (!$currentRoom) {
            throw new NormalStatusException('操作失败');
        }

        // 根据类型进行排序处理
        switch ($type) {
            case 'up':
                $this->moveUp($currentRoom);
                break;

            case 'down':
                $this->moveDown($currentRoom);
                break;

            case 'top':
                $this->moveToTop($currentRoom);
                break;

            case 'bottom':
                $this->moveToBottom($currentRoom);
                break;

            default:
                throw new NormalStatusException('无效的操作类型');
        }
    }

    private function moveUp($currentRoom)
    {
        // 获取同一parent_id下比当前sort值小的最大记录
        $previousRoom = $this->mapper->model::where('uid', $currentRoom->uid)
            ->where('create_user_id', $currentRoom->create_user_id)
            ->where('sort', '<', $currentRoom->sort)
            ->whereNotIn('sort', [0, 1]) // 新增过滤条件
            ->orderByDesc('sort')
            ->first(['id', 'sort']);

        if ($previousRoom) {
            // 交换sort值
            Db::transaction(function () use ($currentRoom, $previousRoom) {
                $tempSort = $currentRoom->sort;
                $currentRoom->sort = $previousRoom->sort;
                $previousRoom->sort = $tempSort;

                $currentRoom->save();
                $previousRoom->save();
            });
        }
    }

    private function moveDown($currentRoom)
    {
        // 获取同一下比当前sort值大的最小记录
        $nextRoom = $this->mapper->model::where('uid', $currentRoom->uid)
            ->where('create_user_id', $currentRoom->create_user_id)
            ->where('sort', '>', $currentRoom->sort)
            ->whereNotIn('sort', [0, 1]) // 新增过滤条件
            ->orderBy('sort')
            ->first(['id', 'sort']);

        if ($nextRoom) {
            // 交换sort值
            Db::transaction(function () use ($currentRoom, $nextRoom) {
                $tempSort = $currentRoom->sort;
                $currentRoom->sort = $nextRoom->sort;
                $nextRoom->sort = $tempSort;

                $currentRoom->save();
                $nextRoom->save();
            });
        }
    }

    private function moveToTop($currentRoom)
    {
        Db::transaction(function () use ($currentRoom) {
            $this->mapper->model::where('uid', $currentRoom->uid)
                ->where('create_user_id', $currentRoom->create_user_id)
                ->where('sort', '<', $currentRoom->sort)
                ->whereNotIn('sort', [0, 1]) // 只处理 sort >=2 的记录
                ->increment('sort');

            $this->mapper->model::where('id', $currentRoom->id)->update(['sort' => 2]);
        });
    }

    private function moveToBottom($currentRoom)
    {
        $maxSort = $this->mapper->model::where('uid', $currentRoom->uid)
            ->max('sort');

        Db::transaction(function () use ($currentRoom, $maxSort) {
            $this->mapper->model::where('uid', $currentRoom->uid)
                ->where('create_user_id', $currentRoom->create_user_id)
                ->where('sort', '>', $currentRoom->sort)
                ->whereNotIn('sort', [0, 1]) // 过滤特殊值
                ->decrement('sort');

            $this->mapper->model::where('id', $currentRoom->id)->update(['sort' => $maxSort]);
        });
    }

    private function updateHumanCeiling($uid, $newMaxNumber)
    {
        // 获取所有需要更新的房间
        $rooms = Db::table('ch_add_friend_room')
            ->where('uid', $uid)
            ->where('status', '<>', 3) // 排除已满的群
            ->get(['id', 'room_wxid', 'human_ceiling']);

        $updateData = [];
        foreach ($rooms as $room) {
            // 获取当前群人数
            $roomInfo = $this->roomMapper->findByRoomWxid($room->room_wxid, $uid);
            if (!$roomInfo) continue;

            $memberCount = (int)$roomInfo->room_member_count;
            $newHumanCeiling = $newMaxNumber - $memberCount;

            // 处理负数情况
            if ($newHumanCeiling < 0) {
                $status = 3;
                $newHumanCeiling = 0;
            } else {
                $status = ($room->human_ceiling <= 0) ? 3 : $room->status;
            }

            $updateData[] = [
                'id' => $room->id,
                'human_ceiling' => $newHumanCeiling,
                'status' => $status,
                'sort' => ($status === 3) ? 0 : $room->sort
            ];
        }

        // 批量更新
        Db::transaction(function () use ($updateData) {
            foreach ($updateData as $data) {
                Db::table('ch_add_friend_room')
                    ->where('id', $data['id'])
                    ->update([
                        'human_ceiling' => $data['human_ceiling'],
                        'status' => $data['status'],
                        'sort' => $data['sort'],
                        'add_number' => 0,
                    ]);
            }
        });

        $this->updateRoomSort($uid); // 触发排序更新
    }
}

